package cn.xm.system.service.impl;

import cn.xm.system.domain.Menu;

import cn.xm.system.service.MenuService;
import cn.xm.basic.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xm
 * @since 2022-10-24
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements MenuService {

    /**
     * 查找一级菜单
     * @return
     */
    @Override
    public List<Menu> first() {
        List<Menu> list = super.findAll();
        // 只取一级部门
        return list.stream().filter(a -> a.getParentId() == null).collect(Collectors.toList());
    }

    @Override
    public List<Menu> getTree() {
        List<Menu> list = super.findAll();
        Map<Long, Menu> map = list.stream().collect(Collectors.toMap(Menu::getId, menu -> menu));
        List<Menu> menus = new ArrayList<>();
        list.forEach(menu -> {
            if (menu.getParentId() == null) {
                menus.add(menu);
            } else {
                Menu parent = map.get(menu.getParentId());
                if (parent == null) return;
                parent.getChildren().add(menu);
            }
        });
        return menus;
    }


}
